package com.xgkj.diyiketang.weidget;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;

public class MoneyInputEditText extends ClearableEditText {

	public float moneyMaxInput = Integer.MAX_VALUE;// = "500";
	public int lenAfterDot=2;// = 2;
//	public float moneyMinInput;

	private int indexCursor;
	String beforeText;

	public MoneyInputEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.addTextChangedListener(mTextWatcher);
		indexCursor = 0;
	}

	private TextWatcher mTextWatcher = new TextWatcher() {
		private boolean isChanged = false;

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			if (isChanged) {// ----->如果字符未改变则返回,否则会resetindexCursor
				return;
			}

			// get the position that start to be replaced by the ‘after’ length
			indexCursor = start;
			beforeText = s.toString();

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable s) {

			if (isChanged) {// ----->如果字符未改变则返回
				return;
			}
			String str = s.toString();
			isChanged = true;

			if (str.length() > 0) {
				int positionFromStart = str.indexOf('.');
				// smaller than moneyMaxInput
				if (positionFromStart >= 0) {
					// find '.'
					int positionFromEnd = (str.length() - 1)
							- str.indexOf('.');
					if (positionFromEnd > lenAfterDot || positionFromStart==0) {

						// set the money
						setText(beforeText);

						// set the focus
						setSelection(indexCursor);
						isChanged = false;
						return;

					}
				}
				
				float strInputFloat = 0;
				try {
					strInputFloat = Float.parseFloat(str);
				} catch (Exception e) {
					e.printStackTrace();
					isChanged = false;
					return;
				}
				if (strInputFloat > moneyMaxInput) {
					// larger than moneyMaxInput

					// set the money
					setText(beforeText);

					// set the focus
					setSelection(indexCursor);

				}
				//else if(strInputFloat < moneyMinInput){
				//	setText(beforeText);
					//setSelection(indexCursor);
				//} 
			else {
					
				}
			}
			isChanged = false;
		}
	};

	public void setNumberStyle(boolean decimal) {
		DigitsKeyListener numericOnlyListener = new DigitsKeyListener(false,
				decimal);
		this.setKeyListener(numericOnlyListener);
	}

	public void setSingleLine() {
		this.setSingleLine(true);
	}

	public void setMoneyMaxInput(float maxMoney) {
		moneyMaxInput = maxMoney;
	}

	public void setLenAfterDot(int num) {
		lenAfterDot = num;
	}
	
//	public void setMoneyMinInput(float minMoney){
//		moneyMinInput = minMoney;
//	}

}
